package com.hyrluntan.forum.controller;

import com.hyrluntan.forum.common.AppResult;
import com.hyrluntan.forum.common.ResultCode;
import com.hyrluntan.forum.exception.ApplicationException;
import com.hyrluntan.forum.model.Board;
import com.hyrluntan.forum.services.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Api(tags = "板块接口")
@RestController
@RequestMapping("/board")
public class BoradController {

    // 从配置⽂件中获取主⻚中显⽰的版块个数，默认为9
    @Value("${hyrforum.index.board-num:9}")
    private Integer indexBoardNum;

    @Resource
    private IBoardService boardService;
    /**
     * 查询首页板块列表
     * @return
     */
    @ApiOperation("获取首页板块列表")
    @GetMapping("/topList")
    public AppResult<List<Board>> topList () {
        System.out.println("indexBoardNum = " + indexBoardNum);
        log.info("首页板块个数为："+indexBoardNum);
        // 调⽤Service层获取版块信息
        List<Board> boards = boardService.selectByNum(indexBoardNum);
        if(boards==null)
            boards = new ArrayList<>();
        // 返回结果
        return AppResult.success(boards);
    }

    @ApiOperation("获取所有正常状态的版块")
    @GetMapping("/allNormal")
    public AppResult<List<Board>> allNormal () {
        // 调⽤Service层获取版块信息
        List<Board> boards = boardService.selectAllNormal();
        // 返回结果
        return AppResult.success(boards);
    }

    /**
     * 获取版块详情
     * @param id 版块 id
     * @return 版块详情
     */
    @ApiOperation("获取版块详情")
    @GetMapping("/getById")
    public AppResult<Board> getBoardInfo (@ApiParam(value = "版块Id") @RequestParam(value = "id") @NonNull Long id) {
        Board board = boardService.selectById(id);
        // 对查询结果进行校验
        if(board==null||board.getDeleteState()==1){
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        return AppResult.success(board);
    }

}
